package com.lorenzogao.latte_core.ui

import android.content.Context
import com.wang.avi.AVLoadingIndicatorView
import com.wang.avi.Indicator
import java.lang.Exception
import java.util.*

/**
 *  create by LorenzoGao
 *  email: 2508719070@qq.com
 *  TIME: 2020-01-08 15:45
 *  description:
 */

class LoaderCreator {


    companion object {
        private val LOADING_MAP = WeakHashMap<String, Indicator>()

        fun create(type: String, context: Context): AVLoadingIndicatorView {
            val avLoadingIndicatorView = AVLoadingIndicatorView(context)
            if (LOADING_MAP.isNullOrEmpty()) {
                val indicator = getIndicator(type)
                LOADING_MAP[type]=indicator
            }
            avLoadingIndicatorView.indicator = LOADING_MAP[type]
            return avLoadingIndicatorView
        }

        private fun getIndicator(name: String): Indicator? {
            if (name.isNullOrEmpty()) {
                return null
            }

            val drawableClassName = StringBuffer()
            if (!name.contains(".")) {
                val defaultPackName = AVLoadingIndicatorView::class.java.`package`?.name ?: ""
                drawableClassName.append(defaultPackName)
                    .append(".indicators")
                    .append(".")
            }
            drawableClassName.append(name)
            return try {
                val drawableClass = Class.forName(drawableClassName.toString())
                drawableClass.newInstance() as Indicator
            } catch (e: Exception) {
                e.printStackTrace()
                null
            }


        }

    }


}